# -*- coding: utf-8 -*-

import os
import hashlib
from django.db import models
from core.models import CoreModel, table_prefix


def media_file_name(instance, filename):
    h = instance.md5sum
    basename, ext = os.path.splitext(filename)
    return os.path.join("files", h[0:1], h[1:2], h + ext.lower())


class OfflineDocument(CoreModel):
    name = models.CharField(null=True, blank=True, max_length=50, verbose_name="名称")
    file = models.FileField(upload_to=media_file_name)
    size = models.IntegerField(default=0, verbose_name="文件大小")
    md5sum = models.CharField(blank=True, max_length=36, verbose_name="文件md5")

    def save(self, *args, **kwargs):
        if not self.md5sum:  # file is new
            md5 = hashlib.md5()
            for chunk in self.file.chunks():
                md5.update(chunk)
            self.md5sum = md5.hexdigest()
        super(OfflineDocument, self).save(*args, **kwargs)

    class Meta:
        db_table = table_prefix + "system_offline_document"
        verbose_name = "离线文件"
        verbose_name_plural = verbose_name
        ordering = ("-create_time",)
